package com.boyou.sytzc.api.core;

import android.os.Build;

import com.boyou.sytzc.BuildConfig;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * HttpApi管理类
 */
public class HttpApiManager {

	private HashMap<Class, Object> httpApiCache = new HashMap<>();
	private Retrofit retrofit;

	/**
	 * 构造函数
	 */
	private HttpApiManager() {
		retrofit = new Retrofit.Builder()
			.baseUrl("http://www.baidu.com/")
			.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
			.addConverterFactory(GsonConverterFactory.create())
			.addConverterFactory(NobodyConverterFactory.create())
			.addConverterFactory(NullOrEmptyConverterFactory.create())
			.client(configOkHttpClient())
			.build();
	}

	/**
	 * 配置OkHttpClient参数
	 **/
	@NotNull
	private static OkHttpClient configOkHttpClient() {
		OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
		okHttpClientBuilder.readTimeout(20, TimeUnit.SECONDS);
		okHttpClientBuilder.writeTimeout(60, TimeUnit.SECONDS);
		okHttpClientBuilder.addInterceptor(chain -> {
			Request originalRequest = chain.request();
			return chain.proceed(originalRequest.newBuilder()
				.addHeader("app_version", String.valueOf(BuildConfig.VERSION_CODE))
				.addHeader("app_version_name", BuildConfig.VERSION_NAME)
				.addHeader("device_os", "android")
				.addHeader("device_version", Build.VERSION.RELEASE)
				.addHeader("device_model", Build.MODEL)
				.addHeader("device_manufacturer", Build.MANUFACTURER)
				.addHeader("device_brand", Build.BRAND)
				.addHeader("device_id", Build.ID)
				.method(originalRequest.method(), originalRequest.body())
				.build());
		});
		if (BuildConfig.DEBUG) { //DEBUG模式下添加 HttpLoggingInterceptor
			try {
				Class clazz = Class.forName("okhttp3.logging.HttpLoggingInterceptor");
				Object loggingInterceptorInstance = clazz.newInstance();
				Method addInterceptorMethod = okHttpClientBuilder.getClass().getMethod("addInterceptor", Interceptor.class);
				//noinspection JavaReflectionInvocation
				addInterceptorMethod.invoke(okHttpClientBuilder, loggingInterceptorInstance);
				Class levelEnum = Class.forName("okhttp3.logging.HttpLoggingInterceptor$Level");
				Field bodyField = levelEnum.getDeclaredField("BODY");
				clazz.getMethod("setLevel", Class.forName("okhttp3.logging.HttpLoggingInterceptor$Level"))
					.invoke(loggingInterceptorInstance,
						bodyField.get(null));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return okHttpClientBuilder.build();
	}

	;

	/**
	 * 获取Api接口服务
	 *
	 * @param clazz API接口定义
	 * @param <T>   API接口定义的泛型类
	 */
	@SuppressWarnings("unchecked")
	public <T> T getService(Class<T> clazz) {
		if (httpApiCache.containsKey(clazz))
			return (T) httpApiCache.get(clazz);
		T t = retrofit.create(clazz);
		httpApiCache.put(clazz, t);
		return t;
	}

	private static HttpApiManager httpApiManager;

	/**
	 * 获取HttpApiManager对象，使用无参数构造函数初始化
	 *
	 * @return HttpAPiManage对象
	 */
	@SuppressWarnings("unchecked")
	public static HttpApiManager getInstance() {
		if (httpApiManager == null) {
			synchronized (HttpApiManager.class) {
				httpApiManager = new HttpApiManager();
			}
		}
		return httpApiManager;
	}

	/**
	 * 获取API接口服务
	 *
	 * @param clazzT API接口
	 * @param <T>    API服务泛型对象
	 * @return API服务对象
	 */
	public static <T> T getApiService(Class<T> clazzT) {
		return getInstance().getService(clazzT);
	}

}